package stream.day0330;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 请将文本信息恢复顺序。(出师表.txt)
 * 步骤：
 *
 * 使用流对象逐行读取原文本信息,把读取的信息保存到集合中
 * 使用Collections集合工具类中的方法sort,对集合中的元素按照自定义规则排序
 * 遍历集合,把集合中排序后的文本在写入到新的记事本中
 */
public class Demo1 {
    public static void main(String[] args) throws IOException {
        FileReader fr = null;
        BufferedReader br = null;
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fr = new FileReader("D:\\马老师\\practice\\jdbc\\stream\\day0330\\出师表.txt");
            br = new BufferedReader(fr);
            fw = new FileWriter("D:\\马老师\\practice\\jdbc\\stream\\day0330\\出师表1.txt");
            bw = new BufferedWriter(fw);
           String line = br.readLine();
            List<String> list= new ArrayList<>();
           while (line != null) {
               list.add(line);
               line = br.readLine();
           }
            list.forEach(e1 -> {
                System.out.println(e1);
            });
           Collections.sort(list, new Comparator<String>() {
               @Override
               public int compare(String o1, String o2) {
                   String s1 = o1.substring(0,o1.indexOf("."));
                   String s2 = o2.substring(0,o2.indexOf("."));
                   return Integer.parseInt(s1) - Integer.parseInt(s2);
               }
           });
            for (String s : list) {
                bw.write(s);
                bw.newLine();
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (br != null) {
                br.close();
            }
          if (fr != null) {
              fr.close();
          }
          if (bw != null){
              bw.close();
          }
          if (fw != null){
              fw.close();
          }

        }
    }
}
